package com.dmgis.qxfw.dataservice.businessservice.yyly.controller;


import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.yyly.service.IForestryfcstService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/xtly")
public class FileController {
	private  final String operatingSystem;

	@Autowired
	public FileController(String operatingSystem) {
		this.operatingSystem = operatingSystem;
	}

	@Resource
	private IForestryfcstService forestryfcstService;

	MongoService1 ms = new MongoService1();

	@RequestMapping(value = "download", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// 1.获取要下载的文件的绝对路径
		String date = request.getParameter("date");// 获取日期
		List<base_product> resultList = forestryfcstService.getServiceDoc(date);
		String docpath = "";
		String servicePath = "";// 服务器文件
		String localPath = "";
		String fileName = "";
		if (resultList != null && resultList.size() > 0) {
			String id = resultList.get(0).getId().toString();
			docpath = resultList.get(0).getProductname();
			String urlpath;
			if (operatingSystem.equals("Windows")){
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Service\\";// 临时文件目录
			}else {
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Service/";// 临时文件目录
			}

			FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
			FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
			// 2.获取要下载的文件名
			fileName = docpath.split("\\\\")[docpath.split("\\\\").length - 1];// 文件名
			String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
			localPath = urlpath + fileName;
			if (doctype.contains("doc")) {
				String pdfPath = urlpath + fileName.replace(doctype, "pdf");
				File pdfFile = new File(pdfPath);
				if (pdfFile.exists()) {
					if (operatingSystem.equals("Windows")){
						servicePath = "Temp\\Service\\" + fileName.replace(doctype, "pdf");
					}else {
						servicePath = "Temp/Service/" + fileName.replace(doctype, "pdf");
					}

				} else {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", id);
					map.put("table_name", "base_product");
					map.put("collectionName", "pdf_file");
					map.put("advCode", DbConfig.advCode);
					byte[] data = ms.selectData(map);
					// 下载doc文件
					if (data == null) {
						servicePath = "";
					}
					FileUtil.bytesToFile(data, localPath);
					File localFile = new File(localPath);// 本地文件
					if (localFile.exists()) {
						if (operatingSystem.equals("Windows")){
							servicePath = "Temp\\Service\\" + fileName.replace(doctype, "pdf");
						}else {
							servicePath = "Temp/Service/" + fileName.replace(doctype, "pdf");
						}
					}
				}
			}
		}
		if (!servicePath.equals("")) {
			response.reset();
			response.setContentType("application/octet-stream");
			// 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			InputStream in = new FileInputStream(localPath);// 获取文件输入流
			int len = 0;
			byte[] buffer = new byte[1024];
			OutputStream out = response.getOutputStream();
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);// 将缓冲区的数据输出到客户端浏览器
			}
			in.close();
		} else {
			response.setContentType("text/html; charset=UTF-8"); // 转码
			PrintWriter out = response.getWriter();
			out.flush();
			out.println("<script>");
			out.println("alert('文件不存在，无法下载文件！');");
			out.println("history.back();");
			out.println("</script>");
		}
	}
}